<?php

declare(strict_types=1);

namespace App\Controller;

use App\Annotation\PreAuth;
use App\Annotation\LogAnnotation;
use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Industry;
use App\Model\Channel;
use App\Service\ChannelService;
use Hyperf\Validation\Rule;
use Hyperf\DbConnection\Db;
Use Hyperf\Di\Annotation\Inject;
use App\Service\IndustryService;
use Psr\Http\Message\ResponseInterface;

class ChannelController extends AbstractController
{
    public function list(ChannelService $ChannelService)
    {
        $params = $this->request->inputs(['key_word','is_show','ids','current','size']);
        $Channel = New Channel();
        $fields = ['*'];

        $key_word = isset($params['key_word'])?$params['key_word']:'';
        $is_show = isset($params['is_show'])?$params['is_show']:'';
        $ids = $params['ids']?$params['ids']:[];
        $where = [];
        if($is_show!==''){
            $where['is_show'] = $is_show;
        }
        $Channel_ids = [];$list = [];
        if($ids){
            $Channel_ids = $ChannelService->linkfind($ids);
        }
        $count = $Channel
            ->where($where)
            ->where(function ($query) use ($key_word) {
                if (!empty($key_word)) {
                    $query->where('channel_name', 'like', '%' . $key_word . '%');
                }
            })
            ->where(function ($query) use ($ids,$Channel_ids) {
                if ($ids!==[]) {
                    $query->whereIn('id',$Channel_ids);
                }
            })
            ->count();
        if($count>0){
            $industry_model = $Channel
                ->where($where)
                ->where(function ($query) use ($key_word) {
                    if (!empty($key_word)) {
                        $query->where('channel_name', 'like', '%' . $key_word . '%');
                    }
                })
                ->where(function ($query) use ($ids,$Channel_ids) {
                    if ($ids!==[]) {
                        $query->whereIn('id',$Channel_ids);
                    }
                })
                ->with(['create_info','update_info','province','city','area','street','link_industry','file_info'])
                ->orderBy('sort','desc')
                ->orderBy('id','desc')
                ->select($fields);
            $list = $this->paginate($industry_model);
        }
//        这里缓存的关联查询有点问题 先用旧方法
//        $list = $ChannelService->get_list($params);
//        $return = [
//            'list' => $list,
//        ];
        return $this->jsonResponse->success($list, '获取列表成功');
    }


    public function add(ChannelService $ChannelService)
    {
        $params = $this->request->inputs(['channel_name','fileinfo_id','description','sort','industry']);
        $this->validation(
            $params,
            [
                'channel_name' => [
                    "required",
                    "string",
                    "max:50",
                ],
                'fileinfo_id' => [
                    "exists:fileinfo,fileinfo_id",
                    "min:0",
                ],
                'description' => 'string|max:255',
                'industry' => "required|array|min:1",
                'industry.*' => [
                    "required",
                    "distinct",
                    "integer",
                    "min:0",
                    Rule::exists('fly_industry','id')->whereNull('deleted_at'),
                ],
            ],
        );

        $admin_id =  parent::getAdminId();
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = $admin_id;
        try{
            Db::beginTransaction();
            $ChannelService->insert($params);
            Db::commit();
            return $this->jsonResponse->success([],'添加成功');
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败'.$exception->getMessage());
        }
    }

    public function edit(ChannelService $ChannelService)
    {
        $params = $this->request->inputs(['id','channel_name','fileinfo_id','description','sort','industry']);
        $this->validation(
            $params,
            [
                'id' => [
                    "required",
                    "integer",
                    "min:1",
                    Rule::exists('fly_channel','id')->whereNull('deleted_at')
                ],
                'channel_name' => [
                    "required",
                    "string",
                    "max:50",
                    Rule::unique('fly_channel','id')->whereNull('deleted_at')->ignore($params['id']),
                ],
                'fileinfo_id' => [
                    "exists:fileinfo,fileinfo_id",
                    "min:0",
                ],
                'description' => 'string|max:255',
                'industry' => "required|array|min:1",
                'industry.*' => [
                    "required",
                    "distinct",
                    "integer",
                    "min:0",
                    Rule::exists('fly_industry','id')->whereNull('deleted_at'),
                ],
            ],
            );
        $admin_id =  parent::getAdminId();
        $params['updated_at'] = date('Y-m-d H:i:s');
        $params['update_by'] = $admin_id;
        try{
            Db::beginTransaction();
            $ChannelService->update($params);
            Db::commit();
            return $this->jsonResponse->success([],'修改成功');
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败'.$exception->getMessage());
        }
    }
    /**
     * @param ChannelService $ChannelService
     * @return ResponseInterface
     */
    public function detail(ChannelService $ChannelService)
    {
        $id = $this->request->input('id');
        $this->validation(
            ['id'=>$id],
            [
                'id' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_channel','id')->whereNull('deleted_at'),
                ],
            ],
        );
        try{
           $info =  (New Channel())
                ->with(['create_info','update_info','province','city','area','street','link_industry'])
                ->find($id);
            return $this->jsonResponse->success($info,'信息返回');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'不存在或已删除：'.$exception->getMessage());
        }

    }

    /**
     * @param ChannelService $ChannelService
     * @return ResponseInterface
     */
    public function del(ChannelService $ChannelService)
    {
        $ids = $this->request->input('ids');
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_channel','id')->whereNull('deleted_at'),
//                     //需要验证没有关联的数据表
//                    Rule::unique('fly_channel','project_id')->where(function ($query) {
//                        $query->where('tenant_id',$tenantId)
//                            ->whereNull('deleted_at');
//                    }),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]

        );
        try{
            $ChannelService->deleteByUser($ids,$this->getAdminId(),3);
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }

    }

    /**
     * @param ChannelService $ChannelService
     * @return ResponseInterface
     */
    public function change_show(ChannelService $ChannelService)
    {
        $ids = $this->request->input('ids');
        $is_show = $this->request->input('is_show');
        $this->validation(
            [
                'ids'=>$ids,
                'is_show'=>$is_show
            ],
            [
                'is_show' => 'required|boolean',
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_channel','id')->whereNull('deleted_at')
                ],
            ],
        );
        try{
            $ChannelService->change_show($ids,boolval($is_show),$this->getAdminId());
            return $this->jsonResponse->success([],'修改成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败:'.$exception->getMessage());
        }

    }

}